//
//  RankMainHeadView.m
//  CoolTennisBall
//
//  Created by Coollang on 2017/7/27.
//  Copyright © 2017年 CoolLang. All rights reserved.
//

#import "RankMainHeadView.h"
#import "CoollangTennisBall-Swift.h"
#import "UIImageView+CM_ShowImage.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "Masonry.h"
#import "MyRankInfoModel.h"

@interface RankMainHeadView ()

@property (weak, nonatomic) IBOutlet UIView *rankCupSuperView;
// 按123排名
@property (strong, nonatomic) IBOutletCollection(DesignableImageView) NSArray *headIconImags;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *otherNameLabel;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *otherDataLabel;

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *otherLocationLabels;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *otherLikeCountLabels;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *otherLikeButtons;

// my
@property (weak, nonatomic) IBOutlet DesignableImageView *myHeadIconImg;
@property (weak, nonatomic) IBOutlet UILabel *myTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *myRankLabel;
@property (weak, nonatomic) IBOutlet UIButton *myrankChangeLabel;
@property (weak, nonatomic) IBOutlet UILabel *myDataLabel;
@property (weak, nonatomic) IBOutlet UILabel *myDZCountLabel;
@property (weak, nonatomic) IBOutlet UIView *myUploadHeadIconView;
@property (weak, nonatomic) IBOutlet UILabel *myUploadImageDescLabel;
@property (weak, nonatomic) IBOutlet UIButton *myLikeButton;


@property (nonatomic, strong) NSArray <RankingModel *>*topThreeRankItems;
@property (nonatomic, strong) MyRankInfoModel *myModel;


@end

@implementation RankMainHeadView

- (void)updateRankHeadView:(NSArray <RankingModel *>*)rankItems withMyranInfoModel:(MyRankInfoModel *)myModel rankModelType:(RankModeType)rankType {
    
    if (rankItems.count < 3){
        NSMutableArray *arrM = [NSMutableArray array];
        [arrM addObjectsFromArray:rankItems];
        for (NSInteger i = rankItems.count; i < 3; i++) {
            [arrM addObject:[[RankingModel alloc] init]];
        }
        rankItems = arrM.copy;
    }
    
    self.topThreeRankItems = rankItems;
    self.myModel = myModel;
    for (NSInteger i = 0; i < rankItems.count; i++) {
        if (i >= 3) {
            break;
        }
        RankingModel *rankModel = rankItems[i];
        [self.headIconImags[i] sd_setImageWithURL:[NSURL URLWithString:rankModel.headIcon] placeholderImage:[UIImage imageNamed:@"competition_icon_defaulImage"]];
        UILabel *nameLabel = self.otherNameLabel[i];
        nameLabel.text = rankModel.userName;
        UIButton *locationBtn = self.otherLocationLabels[i];
        locationBtn.hidden = rankModel.address.length <= 0;
        [locationBtn setTitle:[NSString stringWithFormat:@" %@",rankModel.address] forState:UIControlStateNormal];
        
        UILabel *likesLabel = self.otherLikeCountLabels[i];
        likesLabel.text = rankModel.likes;
        likesLabel.hidden = rankModel.likes.integerValue <= 0;
        UILabel *dataLabel = self.otherDataLabel[i];
        UIButton *likeBtn = self.otherLikeButtons[i];
        likeBtn.selected = rankModel.isLiked;
        
        switch (rankType) {
            case RankModeTypeSwings:{
                dataLabel.attributedText = [self attriValueStr:rankModel.totalCount unitStr:NSLocalizedString(@"Sport.Unit.Shots", nil)];
            }
                break;
            case RankModeTypeMaxSpeed:{
                dataLabel.attributedText = [self attriValueStr:rankModel.maxSpeed unitStr:@"km/h"];
            }
                break;
            case RankModeTypeAvgScore:{
                dataLabel.attributedText = [self attriValueStr:rankModel.score unitStr:NSLocalizedString(@"Unit.Score", nil)];
            }
                break;
        }
    }
    
    if (myModel.headIcon.length > 0){
        self.myRankLabel.text = @(myModel.number).stringValue;

        [self.myHeadIconImg sd_setImageWithURL:[NSURL URLWithString:myModel.headIcon] placeholderImage:[UIImage imageNamed:@"competition_icon_defaulImage"] options:SDWebImageRetryFailed|SDWebImageLowPriority];

        if (myModel.rankChange > 0) {
            [self.myrankChangeLabel setImage:[UIImage imageNamed:@"rank_up"] forState:UIControlStateNormal];
        }else {
            [self.myrankChangeLabel setImage:[UIImage imageNamed:@"rank_down"] forState:UIControlStateNormal];
        }
        
        [self.myrankChangeLabel setTitle:[NSString stringWithFormat:@" %zd",labs(myModel.rankChange)] forState:UIControlStateNormal];
        
        self.myDZCountLabel.text = myModel.likes;
        self.myUploadHeadIconView.hidden = YES;
        switch (rankType) {
            case RankModeTypeSwings:{
                self.myDataLabel.attributedText = [self attriValueStr:myModel.totalCount unitStr:NSLocalizedString(@"Sport.Unit.Shots", nil)];
            }
                break;
            case RankModeTypeMaxSpeed:{
                self.myDataLabel.attributedText = [self attriValueStr:myModel.maxspeed unitStr:@"km/h"];
            }
                break;
            case RankModeTypeAvgScore:{
                self.myDataLabel.attributedText = [self attriValueStr:myModel.maxScore unitStr:NSLocalizedString(@"Unit.Score", nil)];
            }
                break;
        }
        
        [self setMyLikeUserList:myModel.likeUserList];
    }else {
        self.myUploadHeadIconView.hidden = false;
    }
}

- (void)setMyLikeUserList:(NSArray *)userlikeList {
    
    NSInteger maxShowCount = (kYFScreenWidth > 375) ? 5:6;
    NSString *mainStr = [userlikeList componentsJoinedByString:@"、"];
    NSString *subStr = @"";
    if (userlikeList.count == 0){
       mainStr = NSLocalizedString(@"No Like yet", nil);
    }else if (userlikeList.count <= maxShowCount){
        subStr = [NSString stringWithFormat:@"\n%zd%@",userlikeList.count,NSLocalizedString(@"friends recently praised me", "位好友最近赞了我")];
    }else {
        subStr = [NSString stringWithFormat:@"%@\n%zd%@",NSLocalizedString(@"etc.", @"等,"),userlikeList.count,NSLocalizedString(@"friends recently praised me", "位好友最近赞了我")];
    }
    
    self.myLikeUserListLabel.attributedText = [NSAttributedString attributedString:[NSString stringWithFormat:@"%@%@",mainStr,subStr] subString:@[mainStr,subStr] colors:@[[UIColor whiteColor],[UIColor colorWithWhite:1.0 alpha:0.8]] fonts:@[[UIFont systemFontOfSize:12],[UIFont systemFontOfSize:10]]];
    
    self.myDZCountLabel.hidden = (userlikeList.count == 0);
    self.myDZCountLabel.text = @(userlikeList.count).stringValue;
}

- (NSAttributedString *)attriValueStr:(NSString *)valueStr unitStr:(NSString *)unit {
    NSString *toatlStr = [NSString stringWithFormat:@"%@%@",valueStr,unit];
    
    NSAttributedString *attr = [NSAttributedString attributedString:toatlStr subString:@[valueStr,unit] colors:@[[UIColor whiteColor],[UIColor whiteColor]] fonts:@[SanFranciscoFont(18),[UIFont systemFontOfSize:10]]];
    return attr;
}

- (void)configureLocalization {
    self.myTipLabel.text = NSLocalizedString(@"Rank.Me", @"我");
    
    NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"Upload your profile picture to get the ranking!", nil)];
    NSAttributedString *uploadText = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Click Upload", nil) attributes:@{
                                                                                                                                     NSUnderlineStyleAttributeName: @1,
                                                                                                                                     NSUnderlineColorAttributeName: kOrangeColor,
                                                                                                                                     NSForegroundColorAttributeName: kOrangeColor  }];
    
    [mutableAttributedString appendAttributedString:uploadText];
    self.myUploadImageDescLabel.attributedText = mutableAttributedString;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [[NSBundle mainBundle] loadNibNamed:@"RankMainHeadView" owner:self options:nil];
        [self addSubview:self.view];
        [self.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self configureLocalization];
    
    UITapGestureRecognizer *uploadHeadImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadHeadiconImage:)];
    self.myUploadHeadIconView.userInteractionEnabled = YES;
    [self.myUploadHeadIconView addGestureRecognizer:uploadHeadImageTap];
}

- (IBAction)uploadHeadiconImage:(UIGestureRecognizer *)sender {
    
    if (_uploadHeadIconImageBlock){
        self.uploadHeadIconImageBlock();
    }
}

- (void)updateHeadIconWithImage:(UIImage *)image {
    if (image != nil ){
        self.myHeadIconImg.image = image;
        self.myUploadHeadIconView.hidden = YES;
    }
}

//tag:30 第一名 31:第二名 32:第三名
- (IBAction)coverButtonClick:(UIButton *)sender {
    if (self.topThreeRankItems.count > (sender.tag - 30)){
        RankingModel *rankItem = self.topThreeRankItems[sender.tag - 30];
        if (self.showUserRankInfoVcBlock && rankItem.userID.length > 1){
            self.showUserRankInfoVcBlock(rankItem, ^(BOOL success) {
                if (success){
                    RankingModel *tempItem = self.topThreeRankItems[sender.tag - 30];
                    UIButton *tempButton = self.otherLikeButtons[sender.tag - 30];
                    UILabel *tempLikesCountLabel = self.otherLikeCountLabels[sender.tag - 30];
                    tempButton.selected = !tempButton.isSelected;
                    
                    [self.topThreeRankItems[sender.tag - 30] setIsLiked:tempButton.selected];
                    NSInteger change = tempButton.isSelected ? 1:-1;
                    NSInteger newlikeCount = tempItem.likes.integerValue + change;
                    [self.topThreeRankItems[sender.tag - 30] setLikes:@(newlikeCount).stringValue];
                    tempLikesCountLabel.text = [self.topThreeRankItems[sender.tag - 30] likes];
                    tempLikesCountLabel.hidden = newlikeCount <= 0;
                }
            });
        }
    }
}

//tag:60 第一名 61:第二名 62:第三名
- (IBAction)likeButtonClick:(UIButton *)sender {
    
    if(self.topThreeRankItems.count > (sender.tag - 60)) {
        RankingModel *rankItem = self.topThreeRankItems[sender.tag - 60];
        if (self.topThreeLikeHandelBlock && rankItem.beingRequest == NO){
            rankItem.beingRequest = YES;
            self.topThreeLikeHandelBlock(rankItem, sender.tag, ^(BOOL success) {
                 rankItem.beingRequest = NO;
                if (success){
                    sender.selected = !sender.isSelected;
                    rankItem.isLiked = sender.isSelected;
                    NSInteger change = sender.isSelected ? 1:-1;
                    NSInteger newlikeCount = rankItem.likes.integerValue + change;
                    rankItem.likes = @(newlikeCount).stringValue;
                    UILabel *tempLikesCountLabel = self.otherLikeCountLabels[sender.tag - 60];
                    tempLikesCountLabel.text = [self.topThreeRankItems[sender.tag - 60] likes];
                    tempLikesCountLabel.hidden = newlikeCount <= 0;
                }
            });
        }
    }
}

- (IBAction)myLikeButtonClick:(UIButton *)sender {
    
    if (self.lookMyLikesHanldeblock){
        BOOL isOpen = self.myReclycelButton.hidden;
//      BOOL isOpen = [sender isEqual:self.myLikeButton];
        self.myReclycelButton.hidden = !isOpen;
        self.lookMyLikesHanldeblock(isOpen);
    }
}


@end
